package com.abc.cloud.service.impl;

import com.abc.cloud.dto.comment.CommentFileUser;
import com.abc.cloud.dto.comment.CommentUser;
import com.abc.cloud.entity.SensitiveWordEntity;
import com.abc.cloud.entity.UserEntity;
import com.abc.cloud.service.SensitiveWordService;
import com.abc.cloud.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.CommentDao;
import com.abc.cloud.entity.CommentEntity;
import com.abc.cloud.service.CommentService;


@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {

    private Map<String, Object> params;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        this.params = params;
        IPage<CommentEntity> page = this.page(
                new Query<CommentEntity>().getPage(params),
                new QueryWrapper<CommentEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public List<CommentUser> getCommentByFileId(Long id) {

        LambdaQueryWrapper<SensitiveWordEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SensitiveWordEntity::getStatus,1);
        // 查出敏感词
        List<SensitiveWordEntity> sensitiveWordEntities  = sensitiveWordService.list(wrapper);
        List<String> wordList = sensitiveWordEntities.stream()
                .map(SensitiveWordEntity::getName)
                .collect(Collectors.toList());

        // 查出文件id对应的pId 为空的评论 ，第一层评论
        LambdaQueryWrapper<CommentEntity> commentEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentEntityLambdaQueryWrapper.eq(CommentEntity::getFileId,id)
                .isNull(CommentEntity::getPId).eq(CommentEntity::getStatus,1);

        // 添加敏感词条件
        if(wordList !=null && ! wordList.isEmpty()){
            for(String w:wordList){
                commentEntityLambdaQueryWrapper.notLike(CommentEntity::getContent,"%"+w+"%");
            }
        }
        // 执行查询
        List<CommentEntity> pidIsNull = commentService.list(commentEntityLambdaQueryWrapper);

        // 查找pid 不为空的回复评论 第二层评论
        LambdaQueryWrapper<CommentEntity> Wrapper1 = new LambdaQueryWrapper<>();
        Wrapper1.eq(CommentEntity::getFileId,id).isNotNull(CommentEntity::getPId).eq(CommentEntity::getStatus,1);

        // 添加敏感词条件
        if(wordList !=null && ! wordList.isEmpty()){
            for(String w:wordList){
                Wrapper1.notLike(CommentEntity::getContent,"%"+w+"%");
            }
        }

        List<CommentEntity> pidIsNotNull = commentService.list(Wrapper1);



        // 返回的结果
        List<CommentUser> commentUsers = new ArrayList<>();
        // 外层遍历第一层评论
        for(CommentEntity commentEntity:pidIsNull){
            // 添加上username 和avatar
            CommentUser commentUser = toCommentUser((commentEntity));
            // 父评论下的子评论
            List<CommentUser> sonList = new ArrayList<>();
            // 遍历子评论
            for(CommentEntity reply:pidIsNotNull){
                // 子评论的ppid 等于了 id 直接添加到下面
                if(reply.getPpId().equals(commentEntity.getId())){
                    CommentUser commentUser1 = toCommentUser(reply);
                    // 获得pid 去查到username ,作为pUsername
                    Long userId = commentService.getById(reply.getPId()).getUserId();
                    commentUser1.setPUsername(userService.getById(userId).getUsername());
                    sonList.add(commentUser1);
                }
            }
//             排序
            List<CommentUser> sortedSonList = sonList.stream()
                    .sorted(Comparator.comparing(CommentUser::getCreateTime))
                    .collect(Collectors.toList());

            commentUser.setCommentUserList(sortedSonList);
            commentUsers.add(commentUser);
        }
        // 排序
        List<CommentUser> sortedList = commentUsers.stream()
                .sorted(Comparator.comparing(CommentUser::getCreateTime).reversed())
                .collect(Collectors.toList());

        return sortedList;


    }



    /**
     *  递归
     * @param parentId
     * @return
     */

    // 递归方法：获取指定父评论下的所有子评论
    private List<CommentUser> getSubComments(Long parentId) {
        LambdaQueryWrapper<CommentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentEntity::getPId, parentId);
        List<CommentEntity> replyComment = commentService.list(wrapper);

        List<CommentUser> subComments = new ArrayList<>();
        for (CommentEntity reply : replyComment) {
            CommentUser commentUser = toCommentUser(reply);
            Long userId = reply.getUserId();
            commentUser.setPUsername(userService.getById(userId).getUsername());
            List<CommentUser> subSubComments = getSubComments(reply.getId());
            commentUser.setCommentUserList(subSubComments);
            subComments.add(commentUser);
        }

        return subComments;
    }
    /**
     *  给Comment实体 添加头像和username ,成 CommentUser
     */
    public CommentUser toCommentUser(CommentEntity commentEntity){
        Long userId = commentEntity.getUserId();
        UserEntity userEntity = userService.getById(userId);
        String username = userEntity.getUsername();
        String avatar = userEntity.getAvatar();

        CommentUser commentUser = new CommentUser();
        BeanUtils.copyProperties(commentEntity,commentUser);
        commentUser.setUsername(username);
        commentUser.setAvatar(avatar);
        return commentUser;
    }

    /**
     *  获取评论列表
     * @param params
     * @return
     */
    @Override
    public PageUtil getCommentList(Map<String, Object> params) {
        Integer pageSize = Integer.parseInt((String)(params.get("pageSize")));   //一页展示多少条
        pageSize = pageSize > 0 ? pageSize : 1;
        Integer currPage = Integer.parseInt((String)params.get("currPage"));     //当前页数
        String searchContent = (String)params.get("searchContent");
        Integer totalCount = baseMapper.getCount(searchContent);        //总记录数
        Integer totalPage = totalCount / pageSize + (totalCount%pageSize > 0 ? 1 : 0);       //总页数

        List<CommentFileUser> commentList = baseMapper.getCommentList((currPage-1)*pageSize ,pageSize,searchContent);


        // 这里面查出来的
        PageUtil pageUtil = new PageUtil(commentList,pageSize,currPage,totalCount,totalPage);
        return pageUtil;
    }


}